<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.class_id"
        placeholder="班级名称"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in classList"
          :key="item.key"
          :label="item.class_name"
          :value="item.id"
        />
      </el-select>
      <el-date-picker
        v-model="listQuery.start_begin_time"
        type="month"
        class="filter-item"
        value-format="yyyy-MM-dd"
        placeholder="开班开始日期"
      ></el-date-picker>
      <el-date-picker
        v-model="listQuery.start_end_time"
        type="month"
        class="filter-item"
        value-format="yyyy-MM-dd"
        placeholder="开班结束日期"
      ></el-date-picker>
      <el-date-picker
        v-model="listQuery.sign_begin_time"
        type="date"
        class="filter-item"
        value-format="yyyy-MM-dd"
        placeholder="报名开始日期"
      ></el-date-picker>
      <el-date-picker
        v-model="listQuery.sign_end_time"
        type="date"
        class="filter-item"
        value-format="yyyy-MM-dd"
        placeholder="报名结束日期"
      ></el-date-picker>
      <el-select
        v-model="listQuery.fee_status"
        clearable
        class="filter-item"
        style="width: 130px"
        placeholder="缴费情况"
      >
        <el-option
          v-for="item in feeStatus"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.status"
        placeholder="上课情况"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in studentStatus"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-input
        v-model="listQuery.search"
        placeholder="姓名|手机|微信昵称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :loading="listLoading"
        @click="handleFilter"
      >搜索</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleAdd">
        新增
      </el-button>-->
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button>
      <el-button
        v-waves
        :loading="deleteAllLoading"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        style="float:right;"
        @click="deleteAll"
      >批量删除</el-button>
    </div>

    <el-table
      id="student"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>

      <el-table-column type="index" prop="id" width="60" align="center" sortable="custom" />
      <el-table-column
        label="报名时间"
        prop="created_time"
        align="center"
        width="110"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <span>{{ row.created_time | dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年份" prop="year" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.year }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级" prop="class_name" align="center" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.class_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="sex" min-width="50" align="center">
        <template slot-scope="{row}">
          <span>{{ sexType[row.sex]['display_name'] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name" min-width="80" align="center" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column type="expand" label="详情" align="center" width="50">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="手机号:">
              <span>{{ row.phone }}</span>
            </el-form-item>
            <el-form-item label="籍贯:">
              <span>{{ row.provice + row.city + row.county }}</span>
            </el-form-item>
            <el-form-item label="当前状态:">
              <span>{{ nowStatus[row.now_status]['display_name'] }}</span>
            </el-form-item>
            <el-form-item label="学校:">
              <span>{{ row.school }}</span>
            </el-form-item>
            <el-form-item label="紧急联系人姓名:">
              <span>{{ row.other_name }}</span>
            </el-form-item>
            <el-form-item label="专业:">
              <span>{{ row.major }}</span>
            </el-form-item>
            <el-form-item label="紧急联系人电话:">
              <span>{{ row.other_phone }}</span>
            </el-form-item>
            <el-form-item label="学历:">
              <span>{{ row.education }}</span>
            </el-form-item>
            <el-form-item label="紧急联系人关系:">
              <span>{{ row.other_relation }}</span>
            </el-form-item>
            <el-form-item label="备注:">
              <span>{{ row.remarks }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        v-if="roles.includes('admin') || roles.includes('treasurer')"
        label="应收学费"
        prop="receivable_fee"
        width="110"
        align="center"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <el-input
            v-model="row.receivable_fee"
            class="edit-input"
            size="small"
            @blur="editMoney(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="roles.includes('admin') || roles.includes('treasurer')"
        label="实收学费"
        prop="receipts_fee"
        width="110"
        align="center"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <el-input
            v-model="row.receipts_fee"
            class="edit-input"
            size="small"
            @blur="editMoney(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="roles.includes('admin') || roles.includes('treasurer')"
        label="欠款"
        prop="receivable_fee"
        width="90"
        align="center"
      >
        <template slot-scope="{row}">
          <span :style="{ color: row.receivable_fee - row.receipts_fee > 0 ? 'red' : 'black' }">{{ row.receivable_fee - row.receipts_fee }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" prop="source" width="110" align="center" sortable="custom">
        <template slot-scope="{row}">
          <el-select v-model="row.source" @change="changeSource(row)">
            <el-option
              v-for="item in studentSource"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="sign_end_time" width="80" align="center" sortable="custom">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            <span>{{ studentStatus[row.status]['display_name'] }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button
            v-if="row.status === 0"
            v-loading="row._loading"
            icon="el-icon-success"
            type="primary"
            size="mini"
            @click="changeStatus(row, 1)"
          >通过</el-button>
          <el-button
            v-if="row.status === 0"
            v-loading="row._loading"
            icon="el-icon-error"
            type="danger"
            size="mini"
            @click="changeStatus(row, 2)"
          >拒绝</el-button>
          <el-dropdown trigger="click">
            <el-button size="small">
              <i class="el-icon-more"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <span @click="handleEdit(row)">
                  <i class="el-icon-edit"></i>编辑
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span v-if="row.status === 1" @click="changeStatus(row, 3)">
                  <i class="el-icon-star-off"></i>学习中
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span v-if="row.status === 1 || row.status === 3" @click="changeStatus(row, 4)">
                  <i class="el-icon-star-on"></i>结业
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span v-if="row.status === 1 || row.status === 3" @click="changeStatus(row, 5)">
                  <i class="el-icon-remove"></i>退课
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click="handledelete(row)">
                  <i class="el-icon-delete"></i>删除
                </span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      @pagination="getList"
    />

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="info"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="info.name" />
        </el-form-item>
        <el-form-item label="班级" prop="class_id">
          <el-select v-model="info.class_id" class="filter-item" placeholder="请选择">
            <el-option v-for="item in classList" :key="item.key" :label="item.class_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="info.phone" />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="other_name">
          <el-input v-model="info.other_name" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="other_name">
          <el-input v-model="info.other_phone" />
        </el-form-item>
        <el-form-item label="联系人关系" prop="other_relation">
          <el-input v-model="info.other_relation" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="info.remarks" :autosize="{ minRows: 4, maxRows: 10}" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="dialogLoading" @click="editInfo(info)">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

</style>
<style>
#student .el-table__expand-icon>.el-icon {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -5px;
  margin-top: -5px;
  color: blue;
  font-weight: 900;
  font-size: 14px;
  /* text-decoration: underline; */
}
</style>
<script>
import {
  fetchList,
  fetchAdd,
  fetchEdit,
  fetchDelete,
  fetchDeleteAll,
  fetchDownload
} from '@/api/students';

import waves from '@/directive/waves'; // waves directive
import { parseTime, range, download } from '@/utils';
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
import {
  feeStatus,
  sexType,
  studentStatus,
  nowStatus,
  studentSource
} from '@/utils/dataType';
import {
  fetchList as fetchClassList
} from '@/api/classes'

export default {
  name: 'StudentList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': 'info',
        '1': 'success',
        '2': 'danger',
        '3': 'success',
        '4': 'success',
        '5': 'warning'
      };
      return statusMap[status];
    },
    dateFormat(time) {
      return time === 0 ? '-' : parseTime(time, '{y}-{m}-{d}');
    }
  },
  data() {
    return {
      visible: false,
      tableKey: 0,
      sexType,
      studentStatus,
      nowStatus,
      list: [],
      classList: [],
      total: 0,
      listLoading: true,
      roles: [],
      listQuery: {
        page: 1,
        page_size: 10,
        class_id: undefined,
        class_type: undefined,
        start_begin_time: undefined,
        start_end_time: undefined,
        sign_begin_time: undefined,
        sign_end_time: undefined,
        search: undefined,
        fee_status: undefined,
        status: undefined,
        sort: '-id'
      },
      years: range(2018, 2025),
      dialogTitle: '新增班级',
      info: {},
      feeStatus,
      studentSource,
      downloadLoading: false,
      dialogLoading: false,
      dialogFormVisible: false,
      deleteAllLoading: false,
      multipleSelection: []
    };
  },
  created() {
    this.roles = this.$store.getters.roles || [];
    this.listQuery.class_type = this.$route.meta.class_type;
    this.listQuery.class_id = this.$route.params.id;
    this.getClassList(this.listQuery.class_type);
    this.getList();
  },
  methods: {
    reset() {
      this.listQuery = this.$options.data().listQuery;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async getClassList(class_type) {
      const query = {
        page: 1,
        page_size: 50,
        class_type,
        sort: '-id'
      }
      const { data } = await fetchClassList(query)
      const { data: list } = data
      this.classList = list
    },
    async getList() {
      try {
        this.listLoading = true;
        const { data } = await fetchList(this.listQuery);
        const { data: list, total } = data;
        list.map(v => {
          v._loading = false;
          v._receivable_fee = false;
          v._receipts_fee = false;
        });
        this.list = list;
        this.total = total;
        this.listLoading = false;
      } catch (e) {
        this.listLoading = false;
      }
    },
    editInfo({ id, class_id, phone, other_name, other_phone, other_relation, remarks }) {
      this.edit({ id, class_id, phone, other_name, other_phone, other_relation, remarks })
    },
    editMoney({ id, receipts_fee, receivable_fee }) {
      // vue双向绑定，无法如此判断
      // const find = this.list.find(({ id }) => row.id)
      // if (JSON.stringify(find) === JSON.stringify(row)) {
      //   return 
      // }
      this.edit({ id, receipts_fee, receivable_fee })
    },
    async edit(data) {
      try {
        this.dialogLoading = true;
        await fetchEdit(data);
        this.dialogLoading = false;
        this.$message({ message: '修改成功', type: 'success' });
        this.dialogFormVisible = false;
      } catch (e) {
        this.dialogLoading = false;
      }
    },
    async changeStatus(row, status) {
      let content = '';
      switch (status) {
        case 1:
          content = '通过';
          break;
        case 2:
          content = '拒绝';
          break;
        case 3:
          content = '学习中';
          break;
        case 4:
          content = '结业';
          break;
        case 5:
          content = '退课';
          break;
      }
      this.$confirm(
        `此操作不可恢复，确认要修改【${row.name}】学生状态为【${content}】吗？`
      )
        .then(_ => {
          try {
            (async () => {
              row._loading = true;
              const data = {
                id: row.id,
                status
              };
              await fetchEdit(data);
              row.status = status;
              row._loading = false;
              this.$message({ message: '修改成功', type: 'success' });
            })();
          } catch (e) {
            this.$message({ message: '修改失败', type: 'error' });
            row._loading = false;
          }
        })
        .catch(_ => {});
    },
    async changeSource({ id, source }) {
      try {
        await fetchEdit({ id, source });
        this.$message({ message: '修改成功', type: 'success' });
      } catch {
        this.$message({ message: '修改失败', type: 'error' });
      }
    },
    async add() {
      try {
        this.dialogLoading = true;
        await fetchAdd(this.info);
        this.dialogLoading = false;
        this.$message({ message: '新增成功', type: 'success' });
        this.info = {};
        // this.reset()
        // this.dialogFormVisible = false
        // await this.getList()
      } catch (e) {
        this.dialogLoading = false;
      }
    },
    async deleteAll() {
      if (this.multipleSelection.length) {
        try {
          this.deleteAllLoading = true;
          await fetchDeleteAll({ ids: this.multipleSelection });
          this.$message({ message: '批量删除成功', type: 'success' });
          this.deleteAllLoading = false;
          await this.getList();
        } catch (e) {
          this.deleteAllLoading = false;
        }
      } else {
        this.$message({ message: '没有学生被选中', type: 'error' });
      }
    },
    // handleAdd() {
    //   this.info = {};
    //   this.dialogTitle = '新增学生';
    //   this.dialogFormVisible = true;
    // },
    handleEdit(row) {
      this.info = row;
      this.dialogTitle = '修改学生信息';
      this.dialogFormVisible = true;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handledelete(row) {
      this.$confirm(`此操作不可恢复，确认要删除【${row.name}】学生吗？`)
        .then(_ => {
          try {
            (async () => {
              await fetchDelete(row.id);
              this.$message({ message: '删除成功', type: 'success' });
              await this.getList();
            })();
          } catch (e) {
            this.$message({ message: '删除失败', type: 'error' });
          }
        })
        .catch(_ => {});
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop) {
        this.sort(prop, order);
      } else {
        this.listQuery.sort = '-id';
        this.handleFilter();
      }
    },
    sort(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sort = `+${prop}`;
      } else {
        this.listQuery.sort = `-${prop}`;
      }
      this.handleFilter();
    },
    async handleDownload() {
      try {
        this.downloadLoading = true
        const { data } = await fetchDownload({ ...this.listQuery, xls_type: 2 })
        this.downloadLoading = false
        download(data, `学生信息-${new Date().getTime()}.xlsx`) // url时名字不起作用
      } catch (e) {
        this.downloadLoading = false
      }
      // import('@/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const data = this.formatJson(filterVal, this.list)
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data,
      //     filename: 'table-list'
      //   })
      //   this.downloadLoading = false
      // })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
